package DBLayer;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

import ModelLayer.Employee;
import ModelLayer.Person;

public class DBEmployee implements IFDBEmployee {
	
	private Connection con;
	  
    public DBEmployee() 
    {
       con = DBConnection.getInstance().getDBcon();
    }
    
    public ArrayList<Employee> getAllEmployees()
	{
		return miscWhere("ID = EmployeeID AND Type = 'employee'");
	}
    
    public Employee getEmpById(int id)
    {
    	return singleWhere("ID = " + id);
    }
    
    private Employee singleWhere(String wClause)
	{
		ResultSet results;
		Employee emp = null;
		String query = buildQuery(wClause);
		
		try
		{
			Statement stmt = con.createStatement();
			stmt.setQueryTimeout(5);
			results = stmt.executeQuery(query);
			
			if(results.next())
			{
				emp = buildEmployee(results);
			}
			
			stmt.close();
			
		}
		
		catch(Exception e)
		{
			System.out.println("Query Exception - Select: "+e);
			e.printStackTrace();
		}
		
		return emp;
	}
    
	 //miscWhere is used when more than one TreatmentCategory is selected and build
    private ArrayList<Employee> miscWhere(String query)
	{
		ResultSet results;
		ArrayList<Employee> list = new ArrayList<Employee>();
		
		String wQuery =  buildQuery(query);
        System.out.println("DbEmployee " + wQuery);
                
  		try 
  		{
	 		Statement stmt = con.createStatement();
	 		stmt.setQueryTimeout(5);
	 		results = stmt.executeQuery(wQuery);
	 		
			
			while(results.next() )
			{
		     	 Employee empObj = new Employee();
		     	 
			     empObj = buildEmployee(results);
			     
                 list.add(empObj);
			}
			
			stmt.close();
		}
	 	catch(Exception e){
	 		System.out.println("Query exception - select TreatmentCategory : "+e);
			e.printStackTrace();
	 	}
  		
		return list;
	}
	
	
    private String buildQuery(String query)
	{
	    String wQuery = "SELECT ID, Type, FirstName, LastName, PhoneNr, Email, DateCreated, Address, City, ZipCode FROM Person, Employee";
		
		if (query.length() > 0)
			wQuery = wQuery + " WHERE " + query;
			
		return wQuery;
	}
    
    private Employee buildEmployee(ResultSet result)
	{
		Employee emp = new Employee();
		
		try 
		{
			emp.setId(result.getInt("ID"));
			emp.setType(result.getString("Type"));
			emp.setFirstName(result.getString("FirstName"));
			emp.setLastName(result.getString("LastName"));
			emp.setPhone(result.getString("Phone"));
			emp.setDateCreated(result.getDate("DateCreated"));
			emp.setAddress(result.getString("Address"));
			emp.setCity(result.getString("City"));
			emp.setZipCode(result.getInt("ZipCode"));
			emp.setEmail(result.getString("Email"));
		}
		catch(Exception err)
		{	
			
		}
		
		return emp;
	}
}
